<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/default}">
<head>
    <title>仪表盘</title>
    <style>
        .stats-card {
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
            background-color: white;
            margin-bottom: 1.5rem;
        }
        
        .stats-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary-color);
            margin-bottom: 0.5rem;
        }
        
        .stats-title {
            color: var(--gray-color);
            margin: 0;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1.5rem;
        }
        
        .chart-container {
            background-color: white;
            border-radius: 0.5rem;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        @media (max-width: 1200px) {
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <h1>仪表盘</h1>
        <p>欢迎使用CRM系统，这里是您的业务概览。</p>
        
        <!-- 统计卡片 -->
        <div class="stats-grid">
            <div class="stats-card">
                <div class="stats-icon">👥</div>
                <div class="stats-number" id="totalCustomers">-</div>
                <h3 class="stats-title">客户总数</h3>
            </div>
            
            <div class="stats-card">
                <div class="stats-icon">💰</div>
                <div class="stats-number" id="totalOpportunities">-</div>
                <h3 class="stats-title">销售机会</h3>
            </div>
            
            <div class="stats-card">
                <div class="stats-icon">📝</div>
                <div class="stats-number" id="newCustomers">-</div>
                <h3 class="stats-title">本月新增客户</h3>
            </div>
            
            <div class="stats-card">
                <div class="stats-icon">💵</div>
                <div class="stats-number" id="expectedRevenue">-</div>
                <h3 class="stats-title">预期收入</h3>
            </div>
        </div>
        
        <!-- 最近活动 -->
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">最近活动</h2>
            </div>
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width: 20%">活动</th>
                            <th style="width: 25%">客户</th>
                            <th style="width: 15%">状态</th>
                            <th style="width: 20%">时间</th>
                        </tr>
                    </thead>
                    <tbody id="recentActivities">
                        <tr>
                            <td colspan="4" class="text-center">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 销售漏斗 & 销售趋势 -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
            <div class="chart-container">
                <h3>销售漏斗</h3>
                <p>各阶段销售机会分布</p>
                <div id="salesFunnel" style="height: 250px; background-color: #f8f9fa; border-radius: 4px; display: flex; justify-content: center; align-items: center;">
                    加载中...
                </div>
            </div>
            
            <div class="chart-container">
                <h3>销售趋势</h3>
                <p>近6个月销售情况</p>
                <div id="salesTrend" style="height: 250px; background-color: #f8f9fa; border-radius: 4px; display: flex; justify-content: center; align-items: center;">
                    加载中...
                </div>
            </div>
        </div>
    </div>
    
    <th:block layout:fragment="scripts">
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                // 加载客户统计数据
                fetch('/crm/api/customer/statistics')
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            document.getElementById('totalCustomers').textContent = data.data.totalCustomers || 0;
                            document.getElementById('newCustomers').textContent = data.data.newCustomersThisMonth || 0;
                        } else {
                            console.error('加载客户统计数据失败:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('加载客户统计数据出错:', error);
                    });
                
                // 加载销售机会统计数据
                fetch('/crm/api/opportunity/statistics')
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            document.getElementById('totalOpportunities').textContent = data.data.totalOpportunities || 0;
                            
                            // 格式化预期收入为货币格式
                            const expectedRevenue = data.data.expectedRevenue || 0;
                            document.getElementById('expectedRevenue').textContent = `¥${formatNumber(expectedRevenue)}`;
                            
                            // 更新销售漏斗数据
                            updateSalesFunnel(data.data.stageCounts);
                        } else {
                            console.error('加载销售机会统计数据失败:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('加载销售机会统计数据出错:', error);
                    });
                
                // 加载合同金额趋势
                fetch('/crm/api/contract/amount-trend?months=6')
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            updateSalesTrend(data.data);
                        } else {
                            console.error('加载合同金额趋势失败:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('加载合同金额趋势出错:', error);
                    });
                
                // 加载最近活动
                loadRecentActivities();
            });
            
            // 格式化数字显示（添加千位分隔符）
            function formatNumber(num) {
                return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }
            
            // 更新销售漏斗图表
            function updateSalesFunnel(stageData) {
                if (!stageData) return;
                
                const funnelElement = document.getElementById('salesFunnel');
                funnelElement.innerHTML = '';
                
                // 简单的阶段展示，实际项目中可以使用图表库如ECharts或Chart.js
                const stageNames = {
                    1: '初步接洽', 
                    2: '需求确认', 
                    3: '方案制定', 
                    4: '商务谈判', 
                    5: '赢单', 
                    6: '输单'
                };
                
                const container = document.createElement('div');
                container.style.width = '100%';
                container.style.padding = '10px';
                
                Object.keys(stageData).forEach(stage => {
                    const stageName = stageNames[stage] || `阶段${stage}`;
                    const count = stageData[stage] || 0;
                    
                    const stageBar = document.createElement('div');
                    stageBar.style.marginBottom = '10px';
                    
                    const label = document.createElement('div');
                    label.textContent = `${stageName}: ${count}`;
                    label.style.marginBottom = '5px';
                    
                    const barOuter = document.createElement('div');
                    barOuter.style.backgroundColor = '#e9ecef';
                    barOuter.style.borderRadius = '4px';
                    barOuter.style.height = '20px';
                    
                    const barInner = document.createElement('div');
                    barInner.style.backgroundColor = '#4361ee';
                    barInner.style.borderRadius = '4px';
                    barInner.style.height = '20px';
                    barInner.style.width = `${(count / 10) * 100}%`; // 假设最大值为10
                    barInner.style.maxWidth = '100%';
                    
                    barOuter.appendChild(barInner);
                    stageBar.appendChild(label);
                    stageBar.appendChild(barOuter);
                    container.appendChild(stageBar);
                });
                
                funnelElement.appendChild(container);
            }
            
            // 更新销售趋势图表
            function updateSalesTrend(trendData) {
                if (!trendData || trendData.length === 0) return;
                
                const trendElement = document.getElementById('salesTrend');
                trendElement.innerHTML = '';
                
                // 简单的趋势展示，实际项目中可以使用图表库
                const container = document.createElement('div');
                container.style.width = '100%';
                container.style.height = '100%';
                container.style.padding = '10px';
                container.style.display = 'flex';
                container.style.alignItems = 'flex-end';
                container.style.justifyContent = 'space-between';
                
                // 找出最大值用于计算高度比例
                const maxAmount = Math.max(...trendData.map(item => item.amount || 0));
                
                trendData.forEach(item => {
                    const monthName = item.month || '';
                    const amount = item.amount || 0;
                    
                    const barContainer = document.createElement('div');
                    barContainer.style.display = 'flex';
                    barContainer.style.flexDirection = 'column';
                    barContainer.style.alignItems = 'center';
                    barContainer.style.width = `${100 / trendData.length}%`;
                    
                    const barOuter = document.createElement('div');
                    barOuter.style.width = '80%';
                    barOuter.style.height = '200px';
                    barOuter.style.display = 'flex';
                    barOuter.style.alignItems = 'flex-end';
                    barOuter.style.justifyContent = 'center';
                    
                    const bar = document.createElement('div');
                    bar.style.width = '70%';
                    bar.style.backgroundColor = '#4361ee';
                    bar.style.borderRadius = '4px 4px 0 0';
                    bar.style.height = `${(amount / maxAmount) * 100}%`;
                    
                    const label = document.createElement('div');
                    label.textContent = monthName;
                    label.style.marginTop = '5px';
                    label.style.fontSize = '12px';
                    
                    const amountLabel = document.createElement('div');
                    amountLabel.textContent = `¥${formatNumber(amount)}`;
                    amountLabel.style.fontSize = '12px';
                    amountLabel.style.marginBottom = '5px';
                    
                    barOuter.appendChild(bar);
                    barContainer.appendChild(amountLabel);
                    barContainer.appendChild(barOuter);
                    barContainer.appendChild(label);
                    container.appendChild(barContainer);
                });
                
                trendElement.appendChild(container);
            }
            
            // 加载最近活动数据
            function loadRecentActivities() {
                // 这里需要后端提供最近活动的API，暂时使用模拟数据
                const activities = [
                    { type: '新增客户', customer: '阿里巴巴', status: 'success', statusText: '完成', time: '2023-05-20 10:30' },
                    { type: '更新联系人', customer: '腾讯科技', status: 'success', statusText: '完成', time: '2023-05-19 15:45' },
                    { type: '添加销售机会', customer: '百度', status: 'primary', statusText: '进行中', time: '2023-05-18 09:15' },
                    { type: '客户回访', customer: '华为技术', status: 'warning', statusText: '待处理', time: '2023-05-17 14:20' },
                    { type: '签约合同', customer: '小米科技', status: 'success', statusText: '完成', time: '2023-05-16 11:10' }
                ];
                
                const tbody = document.getElementById('recentActivities');
                tbody.innerHTML = '';
                
                activities.forEach(activity => {
                    const tr = document.createElement('tr');
                    
                    const typeCell = document.createElement('td');
                    typeCell.textContent = activity.type;
                    
                    const customerCell = document.createElement('td');
                    customerCell.textContent = activity.customer;
                    
                    const statusCell = document.createElement('td');
                    const statusBadge = document.createElement('span');
                    statusBadge.className = `badge badge-${activity.status}`;
                    statusBadge.textContent = activity.statusText;
                    statusCell.appendChild(statusBadge);
                    
                    const timeCell = document.createElement('td');
                    timeCell.textContent = activity.time;
                    
                    tr.appendChild(typeCell);
                    tr.appendChild(customerCell);
                    tr.appendChild(statusCell);
                    tr.appendChild(timeCell);
                    
                    tbody.appendChild(tr);
                });
            }
        </script>
    </th:block>
</body>
</html> 